package com.gjh.concurrency.singleton;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author guangjh
 * @version 1.0
 * @date 2020/7/17 9:24
 */
public class Singleton {
    private static Singleton reference;
    private static final Lock lock = new ReentrantLock();

    public static Singleton getReference() {
        try {
            lock.lock();
            if (reference == null) {
                reference = new Singleton();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
        return reference;
    }

    public static Singleton getReference2() {
        if (reference == null) {
            lock.lock();
            if (reference == null) {
                reference = new Singleton();
            }
            lock.unlock();
        }
        return reference;
    }

    // 使用静态内部类
    private static class LazySingleton {
        private static final Singleton INSTANCE = new Singleton();
    }

    public static Singleton getSingleton() {
        return LazySingleton.INSTANCE;
    }
}
